
package com.yimixian.app.goods;

import com.squareup.picasso.Picasso;
import com.squareup.picasso.RequestCreator;
import com.umeng.analytics.MobclickAgent;
import com.yimixian.app.EventBusDomain.PlusMinusIconMessage;
import com.yimixian.app.R;
import com.yimixian.app.SystemFramework;
import com.yimixian.app.cart.CartDetailActivity;
import com.yimixian.app.cart.CartManager;
import com.yimixian.app.cart.GoodsItemPresenter;
import com.yimixian.app.common.CacheKeys;
import com.yimixian.app.common.Constants;
import com.yimixian.app.common.UMengConstants;
import com.yimixian.app.data.DataManager;
import com.yimixian.app.fragment.DialogGoodDetailFragment;
import com.yimixian.app.model.Banner;
import com.yimixian.app.model.CartUpdate;
import com.yimixian.app.model.GoodDetail;
import com.yimixian.app.model.GoodsItem;
import com.yimixian.app.rest.YmxDataService;
import com.yimixian.app.rest.api.CartUpdateAPI;
import com.yimixian.app.rest.api.GoodDetailAPI;
import com.yimixian.app.ui.AnimationFrameLayout;
import com.yimixian.app.ui.DetailCartView;
import com.yimixian.app.ui.ParabolaView;
import com.yimixian.app.ui.PlusMinusIcon;
import com.yimixian.app.ui.ProgressDialogFragment;
import com.yimixian.app.user.UserRegistrationActivity;
import com.yimixian.app.util.DateUtil;
import com.yimixian.app.util.GlobalLayoutUtils;
import com.yimixian.app.util.UiUtils;

import de.greenrobot.event.EventBus;

import org.json.JSONObject;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import butterknife.ButterKnife;
import butterknife.InjectView;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class GoodDetailFragment extends DialogGoodDetailFragment implements View.OnClickListener,
        IDetailGoodItemSelect,
        GoodsItemPresenter.OnPlusButtonClickListener {
    private final int mGoodDetailRequestIndex=0;
    String mGoodId;
    private LocalBroadcastManager mBroadcastManager;
    private YmxDataService mYmxDataService;
    private ProgressDialogFragment mProgressDialogFragment;
    private AnimationFrameLayout mCart;
    private FrameLayout mPlucMinusIconContainer;
    private Handler mHandler = new Handler();
    private GoodDetailAPI mGoodDetailAPI;

    @InjectView(R.id.tv_detail_title)
    TextView mTvDetailTitle;
    @InjectView(R.id.tv_sub_title)
    TextView mTvSubTitle;
    @InjectView(R.id.tv_good_price)
    TextView mTvGoodPrice;
    @InjectView(R.id.tv_good_price_yuan)
    TextView mTvGoodPriceYuan;
//    @InjectView(R.id.tv_good_price_old)
//    TextView mTvGoodPriceOld;
//    @InjectView(R.id.tv_sale)
//    ImageView mTvSale;
//    @InjectView(R.id.tv_good_desc)
//    TextView mTvGoodDesc;
//    @InjectView(R.id.iv_intro_img)
//    HeightAutoAdjustableImageView mIvIntroImg;
    @InjectView(R.id.sv_good_partner)
    HorizontalScrollView mSvGoodPartner;
    @InjectView(R.id.sv_top)
    HorizontalScrollView mSvTop;
    @InjectView(R.id.ll_partner)
    LinearLayout mLlPartner;
    @InjectView(R.id.ll_top)
    LinearLayout mLlTop;
    @InjectView(R.id.iv_partner_title)
    ImageView mIvPartnerTitle;
    @InjectView(R.id.iv_top_title)
    ImageView mIvTopTitle;
    @InjectView(R.id.ll_banner)
    LinearLayout mLlBanner;
    @InjectView(R.id.iv_back)
    ImageView mIvBack;
    @InjectView(R.id.iv_share)
    ImageView mIvShare;
    @InjectView(R.id.share_layout)
    ShareGoodView mShareLayout;
    @InjectView(R.id.fl_nodata_container)
    FrameLayout mFrameLayoutNoDataContainer;
    @InjectView(R.id.order_no_data)
    View mViewNoData;
    @InjectView(R.id.bottom_cart_view)
    DetailCartView mBottomCartView;
    @InjectView(R.id.divider_view)
    View mDividerView;
    @InjectView(R.id.fl_animation_container)
    FrameLayout mAnimationContainer;

    private int mTotalSelectNum = 0;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_good_detail, null);
        mDialogView = (ViewGroup) view.findViewById(R.id.fl_dialog_container);
        ButterKnife.inject(this, view);

        if(!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().registerSticky(this);
        }
        mGoodId = getArguments().getString(GoodDetailActivity.INTENT_EXTRA_GOOD_ID);
        if (mGoodId == null) {
            UiUtils.showToast(getActivity(), "数据传递失败");
        } else {
            mGoodId = String.valueOf(mGoodId);
        }
        GoodsItem item = null;
        if(CartManager.getInstance().mIdToGoodsItem.get(Integer.parseInt(mGoodId)) != null) {
            item = CartManager.getInstance().mIdToGoodsItem.get(Integer.parseInt(mGoodId));
        }
        mProgressDialogFragment = UiUtils.showProgressDialog(getActivity(), "加载中");
        initData();

        regAddressChangeFinishBroadcast();

        // 添加 +/- 号的组合按钮
        mPlusMinusIcon = new PlusMinusIcon(SystemFramework.getInstance().getGlobalContext(), item,Constants.STATE_DETAILFRAGMENT_BUTTON_BROADCAST);
        mPlucMinusIconContainer.addView(mPlusMinusIcon);
        // 动画执行开关
        // mPlusMinusIcon.setOnPlusButtonClickListener(this);
        // addBestPartnerGoods();
        // addTopGoods();
        setonClickListeners();
//        mTvGoodPriceOld.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
        return view;
    }

    private void initData() {
        mCart = mBottomCartView.getCartViewIcon();
        mPlucMinusIconContainer = mBottomCartView.getPlusMinusContainer();
        mYmxDataService = YmxDataService.getInstance();
        String mGoodDetailRequestKey=GoodDetailAPI.GOOD_DETAIL.replace("{id}", mGoodId);
        setRequestKey(mGoodDetailRequestIndex, mGoodDetailRequestKey);
        fetchData(true, getRequestKeyByIndex(mGoodDetailRequestIndex));
    }

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(this.getClass().getSimpleName());
    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(this.getClass().getSimpleName());
    }

    @Override
    public void onDetach() {
        super.onDetach();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (mLlBanner != null) {
            mLlBanner.removeAllViews();
        }
        if(mPlusMinusIcon != null) {
            mPlusMinusIcon.setEnabled(true);
        }
        mPlusMinusIcon = null;
        EventBus.getDefault().unregister(this);
    }

    /**
     * 初始化页面布局数据
     *
     * @param goodDetail 数据源
     */
    public void initViewWithData(GoodDetail goodDetail) {
        UiUtils.dismiss(mProgressDialogFragment);
        mBottomCartView.setVisibility(View.VISIBLE);
        Good good = goodDetail.good;
        if (goodDetail.good.imgUrl.size() == 0) {
            mLlBanner.setVisibility(View.GONE);
        } else {
            addBannerView(good.imgUrl);
            mLlBanner.setVisibility(View.VISIBLE);
        }
        if (TextUtils.isEmpty(good.title)) {
            mTvDetailTitle.setVisibility(View.GONE);
        } else {
            mTvDetailTitle.setText(good.title);
            mTvDetailTitle.setVisibility(View.VISIBLE);
        }
        if (TextUtils.isEmpty(good.unitDesc) && TextUtils.isEmpty(good.productby)) {
            mTvSubTitle.setVisibility(View.GONE);
        } else {
            if (TextUtils.isEmpty(good.productby) || "null".equals(good.productby)) {
                mTvSubTitle.setText(good.unitDesc);
            } else {
                mTvSubTitle.setText(good.unitDesc + "   " + "产地：" + good.productby);
            }
            mTvSubTitle.setVisibility(View.VISIBLE);
        }
        if (TextUtils.isEmpty(good.unitPrice)) {
            mTvGoodPrice.setVisibility(View.GONE);
        } else {
            mTvGoodPrice.setText(good.unitPrice);
            mTvGoodPriceYuan.setVisibility(View.VISIBLE);
            mTvGoodPrice.setVisibility(View.VISIBLE);
        }

//        if (TextUtils.isEmpty(good.unitOldPrice)) {
//            mTvGoodPriceOld.setVisibility(View.GONE);
//        } else {
//            mTvGoodPriceOld.setText("¥" + good.unitOldPrice);
//            mTvGoodPriceOld.setVisibility(View.VISIBLE);
//        }
//        if (TextUtils.isEmpty(good.promoType)) {
//            mTvSale.setVisibility(View.GONE);
//        } else {
//            Picasso.with(getActivity())
//                    .load(DataManager.getInstance().getImageUrl(good.promoType, 0))
//                    .into(mTvSale);
//            mTvSale.setVisibility(View.VISIBLE);
//        }
//        if (TextUtils.isEmpty(good.funtionDesc)) {
////            mTvGoodDesc.setVisibility(View.GONE);
//        } else {
//            mTvGoodDesc.setText("功效：" + good.funtionDesc);
//            mTvGoodDesc.setVisibility(View.VISIBLE);
//            mDividerView.setVisibility(View.VISIBLE);
//        }
//        if (TextUtils.isEmpty(good.funtionImgurl)) {
//            mIvIntroImg.setVisibility(View.GONE);
//        } else {
//            mIvIntroImg.setImageRatio((float) good.functionRatio);
//            Display display = (getActivity()).getWindowManager().getDefaultDisplay();
//            Point size = new Point();
//            display.getSize(size);
//            int mScreenWidth = size.x;
//            Picasso.with(getActivity())
//                    .load(DataManager.getInstance().getImageUrl(good.funtionImgurl,
//                            mScreenWidth / 2))
//                    .into(mIvIntroImg);
//            mIvIntroImg.setVisibility(View.VISIBLE);
//            mDividerView.setVisibility(View.VISIBLE);
//        }
        mShareLayout.bind(goodDetail.share.title, goodDetail.share.shareurl,
            goodDetail.share.iconImgurl, goodDetail.share.shareContent);
        CartManager.getInstance().sendQuantityChangeBroadCast();
    }

    public void regAddressChangeFinishBroadcast() {
        mBroadcastManager = LocalBroadcastManager.getInstance(SystemFramework
                .getInstance().getGlobalContext());
        IntentFilter filterAddressChange = new IntentFilter();
        filterAddressChange
                .addAction(Constants.BROADCAST_RECEIVE_ADDRESS_CHANGE_FINISH);
        filterAddressChange.addAction(Constants.QUANTITY_CHANGE_BROADCAST);
        filterAddressChange.addAction(Constants.STATE_DETAILFRAGMENT_BUTTON_BROADCAST);
        mBroadcastManager.registerReceiver(mReceiver,
                filterAddressChange);
    }

    BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (Constants.BROADCAST_RECEIVE_ADDRESS_CHANGE_FINISH.equals(intent
                    .getAction())) {
            }
            if (Constants.QUANTITY_CHANGE_BROADCAST.equals(intent.getAction())) {
                int quantity = intent.getExtras().getInt(Constants.QUANTITY_CHANGE, 0);
                if (!mBottomCartView.isBadgeNumberIsNull()) {
                    mBottomCartView.setBadgeIcon(quantity);
                }
            }
            if (Constants.STATE_DETAILFRAGMENT_BUTTON_BROADCAST.equals(intent.getAction())) {
                int state = intent.getExtras().getInt(Constants.GOOD_ID);
                if (state == 0) {
                    showCountLimitDialog();
                } else {
                    float price = intent.getExtras().getFloat(Constants.ITEM_GIGTTYPE_MIN_PRICE);
                    showMoneyLimitDialog(price);
                }
            }
        }
    };

    @Override
    public void onDestroy() {
        if (mReceiver != null && mBroadcastManager != null) {
            mBroadcastManager.unregisterReceiver(mReceiver);
        }
        super.onDestroy();
    }

    public void addBestPartnerGoods() {
        // TODO: size＝0
        // mIvPartnerTitle.setVisibility(View.GONE);

        mLlPartner.removeAllViews();
        for (int i = 0; i < 5; i++) {
            if (isAdded()) {
                GoodsItemView bestPartnerItemView = new GoodsItemView(getActivity());
                bestPartnerItemView.setGoodItemButtonListener(this);
                if (i == 2) {
                    bestPartnerItemView.setSoldOut();
                }
                // TODO:fetch image

                mLlPartner.addView(bestPartnerItemView);
            }
        }

    }

    public void addTopGoods() {
        // TODO: size＝0
        // mIvTopTitle.setVisibility(View.GONE);
        mLlTop.removeAllViews();
        for (int i = 0; i < 5; i++) {
            if (isAdded()) {
                GoodsItemView bestPartnerItemView = new GoodsItemView(getActivity());
                if (i == 0) {
                    bestPartnerItemView.setTop1Icon();
                }
                bestPartnerItemView.setGoodItemButtonListener(this);

                // TODO:fetch image

                mLlTop.addView(bestPartnerItemView);
            }

        }
    }

    @Override
    public void onGoodItemSelect() {
        mTotalSelectNum++;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                if (isAdded()) {
                    getActivity().finish();
                }
                break;
            case R.id.iv_share:
                if (mShareLayout.getVisibility() == View.GONE) {
                    mShareLayout.openShareViewWithAnim();
                }
                break;
            case R.id.cart:
                if (isLogin()) {
                    DateUtil.setCityUMeng(null, UMengConstants.NEW_BOTTOM_CARTBTN);
                     startActivity(CartDetailActivity.buildIntent(getActivity()));
                   /* startActivity(YMXMainActivity.buildIntentTab(getActivity(),
                            YMXMainActivity.TAB_CART));*/
                } else {
                    Intent intent = new Intent(getActivity(), UserRegistrationActivity.class);
                    startActivityForResult(intent, Constants.USER_REGISTRATION_REQUEST_CODE);
                }
                break;
        }
    }

    public void addBannerView(List<String> imgUrl) {
        Log.e("yimixian7", "zheli1");
        if (isAdded()) {
            final BannersView mBannersView = new BannersView(getActivity());
            final List<Banner> banners = new ArrayList<>();
            for (String url : imgUrl) {
                banners.add(new Banner(url, null));
            }

            GlobalLayoutUtils.runAfterLayout(mBannersView, new Runnable() {
                @Override
                public void run() {
                    mBannersView.bind(banners);
                }
            });
            mBannersView.setImageRatio(Float.valueOf("1.5"));
            mLlBanner.addView(mBannersView);
        }
    }

    public void setonClickListeners() {
        mIvBack.setOnClickListener(this);
        mIvShare.setOnClickListener(this);
        mCart.setOnClickListener(this);
    }

    public boolean isLogin() {
        if (DataManager.getInstance().get(CacheKeys.TOKEN) == null) {
            return false;
        }
        return true;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == Constants.USER_REGISTRATION_REQUEST_CODE) {
            startActivity(CartDetailActivity.buildIntent(getActivity()));
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    public ShareGoodView getShareGoodView() {
        if (mShareLayout != null) {
            return mShareLayout;
        }
        return null;
    }

    @Override
    public void onPlusButtonClick(View plusView, Point startPoint, Bitmap animBack) {
        ParabolaView parabolaView = new ParabolaView(getActivity(), animBack);
        mAnimationContainer.addView(parabolaView);
        parabolaView.startAnimation(mHandler, mCart.getCartLocationPoint(), startPoint);
    }

    @Override
    public void initRequestAPI(String requestKeys){
        if (mGoodDetailAPI == null) {
            mGoodDetailAPI = new GoodDetailAPI(mGoodId, this);
        }
        if(requestKeys != null && CartUpdateAPI.CART_UPDATE_API.equals(requestKeys) && mCartUpdateAPI == null) {
            mCartUpdateAPI = new CartUpdateAPI(this);
        }
    }

    @Override
    public void fetchDataFromNetwork(String key) {
        if(CartUpdateAPI.CART_UPDATE_API.equals(key)) {
            initRequestAPI(key);
        } else {
            initRequestAPI(key);
            if (key.equals(getRequestKeyByIndex(mGoodDetailRequestIndex))) {
                mGoodDetailAPI.getGoodDetail();
            }
        }
    }

    @Override
    public void onHttpSuccess(String url, JSONObject responseJson) {
        if (url.contains(getRequestKeyByIndex(mGoodDetailRequestIndex))) {
            GoodDetail goodDetail = mGoodDetailAPI.parseJson(responseJson);
            setGoodDetailData(goodDetail);
        }
        if(mCartUpdateAPI != null) {
            if (url.contains(mCartUpdateAPI.CART_UPDATE)) {
                CartUpdate cartUpdate = mCartUpdateAPI.parseJson(responseJson);
                CartManager.getInstance().updateCartGoods(cartUpdate, mPlusMinusIcon);
                if(mPlusMinusIcon != null) {
                    mPlusMinusIcon.setButtonCanClick(true);
                }
            }
        }
        hidePopupWindow();
    }

    @Override
    public void OnHttpFailure(String url, String errorMessage, boolean errorFromUs) {
        UiUtils.dismiss(mProgressDialogFragment);
        if(mPlusMinusIcon != null) {
            mPlusMinusIcon.setButtonCanClick(true);
        }
        hidePopupWindow();
    }

    public void setGoodDetailData(GoodDetail goodDetail){
        if (goodDetail != null) {
            mFrameLayoutNoDataContainer.setVisibility(View.GONE);
            initViewWithData(goodDetail);
            mIvShare.setVisibility(View.VISIBLE);
        } else {
            mFrameLayoutNoDataContainer.setVisibility(View.VISIBLE);
            ((TextView) mViewNoData.findViewById(R.id.tv_login))
                .setText("联网获取数据失败，请重试");
            mViewNoData.setBackgroundColor(Color.WHITE);
            mViewNoData.findViewById(R.id.rl_login).setVisibility(View.GONE);
            mIvShare.setVisibility(View.GONE);
            UiUtils.dismiss(mProgressDialogFragment);
        }
    }

//    取消dialog框
    public void onEventMainThread(String message) {
        if(message != null) {
                if(Constants.EVENT_BUS_DISSMISS_DIALOG.equals(message)) {
                    hidePopupWindow();
                    if(mPlusMinusIcon != null) {
                        mPlusMinusIcon.setButtonCanClick(true);
                    }
                    EventBus.getDefault().removeStickyEvent(message);
                }
        }
    }

    private void getCartData() {
        fetchUpdateCartData();
        if (mCartUpdateAPI != null) {
            mCartUpdateAPI.getCartInfo();
            showPopupWindow(getActivity(), R.id.popupwindow_container);
        }
    }

    // 发起商品 + / - 的请求
    public void onEventMainThread(PlusMinusIconMessage message) {
        if (message != null) {
            mPlusMinusIcon = message.icon;
            if(Constants.STATE_DETAILFRAGMENT_BUTTON_BROADCAST.equals(message.message)) {
                dealPlusMinusProtocol();
                EventBus.getDefault().removeStickyEvent(message);
            }
        }
    }
}
